# -*- coding: utf-8 -*-
import pymysql
from datetime import datetime
import logging

from resource.MysqlConf import mysql_host
from resource.MysqlConf import mysql_user
from resource.MysqlConf import mysql_password
from resource.MysqlConf import mysql_database

logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s', datefmt='[%Y%m%d-%H:%M:%S]')


# 插入sql
def insert_sql(sql_format, sql_value):
    db = pymysql.connect(host=mysql_host, user=mysql_user, password=mysql_password, database=mysql_database)
    db_curs = db.cursor()
    # insert data insert_sql = """INSERT INTO nginx_log_statistcs(time, type, count, hostname, gmt_created) VALUES (
    # %s,%s,%s,%s,%s);"""
    logging.info(sql_format)
    try:
        db_curs.executemany(sql_format, sql_value)
        db.commit()
        logging.info("数据写入成功。")
    except Exception as e:
        logging.error(e)
        db.rollback()
        logging.error("数据写入失败。")
    db.close()


#  查询sql
def search_sql(sql_format):
    db = pymysql.connect(host=mysql_host, user=mysql_user, password=mysql_password, database=mysql_database)
    db_curs = db.cursor()
    # insert data
    # insert_sql = """INSERT INTO nginx_log_statistcs(time, type, count, hostname, gmt_created)
    # VALUES (%s,%s,%s,%s,%s);"""
    logging.info(sql_format)
    try:
        db_curs.execute(sql_format)
        rows = db_curs.fetchall()
        # db.commit()
        logging.info("数据查询成功。")
    except Exception as e:
        logging.error(e)
        db.rollback()
        logging.error("数据写入失败。")
    db.close()
    return rows


today = datetime.now().strftime("%Y-%m-%d %H:%M:%S")